package com.sneakxy.cloudbase.platform.seata;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.cloud.openfeign.FeignContext;

import com.alibaba.cloud.seata.feign.SeataFeignContext;

public class CloudBaseSeataContextBeanPostProcessor implements BeanPostProcessor {

	private final BeanFactory beanFactory;

	private CloudBaseSeataFeignObjectWrapper seataFeignObjectWrapper;

	public CloudBaseSeataContextBeanPostProcessor(BeanFactory beanFactory) {
		this.beanFactory = beanFactory;
	}

	@Override
	public Object postProcessBeforeInitialization(Object bean, String beanName)
			throws BeansException {
		if (bean instanceof FeignContext && !(bean instanceof SeataFeignContext)) {
			return new CloudBaseSeataFeignContext(getSeataFeignObjectWrapper(),
					(FeignContext) bean);
		}
		return bean;
	}

	@Override
	public Object postProcessAfterInitialization(Object bean, String beanName)
			throws BeansException {
		return bean;
	}

	private CloudBaseSeataFeignObjectWrapper getSeataFeignObjectWrapper() {
		if (this.seataFeignObjectWrapper == null) {
			this.seataFeignObjectWrapper = this.beanFactory
					.getBean(CloudBaseSeataFeignObjectWrapper.class);
		}
		return this.seataFeignObjectWrapper;
	}
	
}
